import json
import logging
import os

import redis.asyncio as redis
from langchain_core.messages import HumanMessage, AIMessage
logger = logging.getLogger(f"app.{__name__}")
# 从环境变量获取 Redis 配置，如果没有则使用默认值
REDIS_HOST = os.getenv("REDIS_HOST", "localhost")
REDIS_PORT = int(os.getenv("REDIS_PORT", 6379))

r = redis.Redis(host=REDIS_HOST, port=REDIS_PORT, db=0, decode_responses=True)

def identify_user_category(current_message: str, chat_history: list) -> str:
    """
    从当前消息或聊天历史中识别用户分类
    Args:
        current_message (str): 当前用户消息
        chat_history (list): 聊天历史记录
    Returns:
        str: 识别到的用户分类，如果未识别到则返回None
    """

    # 定义分类关键词
    category_keywords = {
        "work": ["上班", "工作", "公司", "职员", "工资", "薪水", "朝九晚五"],
        "business": ["个体户", "做生意", "开店", "小商贩", "摆摊", "自营"],
        "business_owner": ["企业", "公司老板", "法人", "董事长", "总经理", "创业"],
        "freelancer": ["自由职业", " freelancer", "自由工作者", "兼职"],
        "student": ["学生", "上学", "大学", "学院", "研究生", "博士"],
        "retiree": ["退休", "养老金", "退休金", "养老"]
    }

    # 检查当前消息
    for category, keywords in category_keywords.items():
        for keyword in keywords:
            if keyword in current_message:
                return category

    # 检查历史消息
    for msg_obj in chat_history[-4:]:  # 检查最近2轮对话
        if isinstance(msg_obj, HumanMessage):
            message_content = msg_obj.content.lower()
            for category, keywords in category_keywords.items():
                for keyword in keywords:
                    if keyword in message_content:
                        return category

    return None


async def get_history_msg(session_id):
    history_key = f"chat:{session_id}"
    chat_history = []
    history_data = await r.get(history_key)
    if history_data:
        try:
            history_list = json.loads(history_data)
            # 将历史记录转换为LangChain消息对象
            for item in history_list:

                if item["role"] == "human":
                    chat_history.append(HumanMessage(content=item["content"]))
                elif item["role"] == "ai":
                    chat_history.append(AIMessage(content=item["content"]))
        except (json.JSONDecodeError, KeyError):
            # 如果解析失败，使用空历史记录
            chat_history = []

    return chat_history


async def get_category(msg, chat_history, session_id):
    user_category_key = f"user_category:{session_id}"
    user_category = await r.get(user_category_key)
    if not user_category:
        user_category = identify_user_category(msg, chat_history)
        if user_category:
            # 将识别到的分类存储到Redis，设置过期时间（例如1小时）
            await r.setex(user_category_key, 3600, user_category)
            logger.info(f"识别到用户分类: {user_category}，已存储到Redis")

    return user_category

